package com.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.service.wx.WxService;
import com.utils.wx.WxReciveMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@CrossOrigin
@Slf4j
public class WeChatController {

    //用于实现微信公众号与服务器的连通
    @GetMapping("/weixin")
    public String weixinGet(HttpServletRequest request) {

        String signature=request.getParameter("signature");
        log.info(signature);
        String timestamp=request.getParameter("timestamp");
        log.info(timestamp);
        String nonce  =request.getParameter("nonce");
        log.info(nonce);
        String echostr  =request.getParameter("echostr");
        log.info(echostr);

        return echostr;
    }


    @Autowired
    private WxService wxService;

    /**
     * 微信公众号  接收普通消息,接收到信息返回
     * https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/weixin")
    public String weixinPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //接收信息
        Map map= WxReciveMsg.parseXml(request);
        String result=wxService.replyMessage(map);
        System.out.println(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(result);
        return null;
    }


/*
    @Value("${natapp.url}")
    private String natappUrl;

    @Value("${wx.appId}")
    private String appid;

    @Value("${wx.appsecret}")
    private String secret;

    @Value("${wx.getCode}")
    private String getCodeUrl;

    private static JSONObject userInfo=new JSONObject();

    @GetMapping("/getCodeUrl")
    private Map<String, Object> toLogin(Model model) throws UnsupportedEncodingException {
        //appid    redirect_uri   state
        String redirect_url=natappUrl+"/wx/login";
        String url=String.format(getCodeUrl,appid, URLEncoder.encode(redirect_url,"UTF-8"),"TEST");
        System.out.println("获取code的"+url);
        return ResUtil.success(url);
    }

    @Value("${wx.getToken}")
    private String getTokenUrl;

    @Value("${wx.getUserInfo}")
    private String getUserInfo;

    //根据code获取    wx访问这个接口
    @GetMapping("/wx/login")
    public void toLoginWx(@RequestParam("code")String code,
                          @RequestParam("state")String state,
                          HttpServletRequest request,
                          HttpServletResponse response) throws IOException, ServletException {

        System.out.println("获取到code"+code);

        //appid  secret   code
        String url=String.format(getTokenUrl,appid,secret,code);
        JSONObject jsonObject= WxUtils.wxGet(url);
        System.out.println(jsonObject);

        String access_token=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");
        //access_token openid
        url=String.format(getUserInfo,access_token,openid);
        jsonObject=WxUtils.wxGet(url);
        System.out.println(jsonObject);
        String nickName=jsonObject.getString("nickname");
        nickName=new String (nickName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
        jsonObject.put("nickname",nickName);
        userInfo=jsonObject;
        response.sendRedirect(natappUrl+"/menu.html?openId="+openid);//重定向 到页面，然后再获取用户信息，需要将用户信息保存到数据库
    }

    @Autowired
    private  JwtTokenUtil jwtTokenUtil;

    @GetMapping("/wx/getUserInfo")
    public Map<String,Object> getUserInfo(@RequestParam("openid")String openid){
        //System.out.println(openid);
        String token=jwtTokenUtil.generateToken(userInfo.getString("openid"));
        *//*String token=jwtTokenUtil.generateToken("username_Test");
        log.info(token);
        log.info(userInfo.toString());
        userInfo.put("nickname","username_Test");*//*
        return ResUtil.success("获取成功",userInfo,token);
    }



    @Value("${wx.getjsapi_ticket}")
    private String getJsTicket;


    //获取js的签名
    @GetMapping("/wx/jsSign")
    public Map<String,Object> validJs(@RequestParam("url")String url) throws IOException {

        String getJsTicketUrl=String.format(getJsTicket, ScheduledComponent.token);
        JSONObject jsonObject=WxUtils.wxGet(getJsTicketUrl);

        String ticket=jsonObject.getString("ticket");

        //生成11位时间戳
        long time11 = System.currentTimeMillis() / 1000;
        String timestamp = String.valueOf(time11);
        //生成16位随机字符串
        String nonce = create16String();
        String string1 = "jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + url;


        String signature = "";
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = encryptSha1(crypt.digest());
        } catch (Exception e) {

        }

        Map<String, String> map = new HashMap<>();
        map.put("signature", signature);
        map.put("timestamp", timestamp);
        map.put("nonce", nonce);
        map.put("url", url);
        map.put("ticket", ticket);
        map.put("appid",appid);


        System.out.println(map);
        return ResUtil.success("js签名",map);
    }

    private String create16String(){
        String a = "ZXCVBNMASDFGHJKLQWERTYUIOPzxcvbnmasdfghjklqwertyuiop0123456789";
        StringBuilder con = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            con.append(a.charAt(random.nextInt(62)));
        }
        return con.toString();
    }

    public String encryptSha1(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }*/

}
